package com.meks.crmi.service;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType;

import com.google.inject.persist.Transactional;
import com.meks.crmi.entities.SparePart;

/**
 * service for handling spare parts.
 * @author mhager
 *
 */
@Singleton
@Transactional
public class SparePartServiceImpl implements SparePartService {
	
	private final EntityManager entityManager;
	
	/**
	 * constructs the service.
	 */
	@Inject
	public SparePartServiceImpl(EntityManager em) {
		this.entityManager = em;
	}
	
	@Override
	public final List<SparePart> getAllSpareParts() {
		CriteriaQuery<SparePart> query = entityManager.getCriteriaBuilder().createQuery(SparePart.class);
		query.from(SparePart.class);
		
		return entityManager
				.createQuery(
						query).getResultList();
	}
	
	@Override
	public final void createSparePart(final SparePart sparePart) {
		entityManager.getTransaction().begin();
		entityManager.persist(sparePart);
		entityManager.getTransaction().commit();
	}

}
